namespace SimpleWebServices.Configuration
{
    using System;
    using System.Configuration;
    using System.Globalization;
    using System.Linq;
    using System.Xml;
    using SimpleWebServices.Models;

    public sealed class InternalServerErrorConfiguration : IConfigurationSectionHandler
    {
        public static InternalServerErrorSettings Settings()
        {
            return InternalServerErrorConfiguration.Settings("simplewebservices/error");
        }

        public static InternalServerErrorSettings Settings(string sectionName)
        {
            return ConfigurationManager.GetSection(sectionName) as InternalServerErrorSettings;
        }

        public object Create(object parent, object configContext, XmlNode section)
        {
            InternalServerErrorSettings result = null;

            if (section != null)
            {
                try
                {
                    result = section.OuterXml.Deserialize<InternalServerErrorSettings>();
                }
                catch (Exception exception)
                {
                    throw new ConfigurationErrorsException(exception.Message, exception, section);
                }

                if ((null != result) && (null != result.Notification))
                {
                    if (null == result.Notification.From)
                    {
                        throw new ConfigurationErrorsException("A <from> element is required.", section);
                    }
                    else if (string.IsNullOrEmpty(result.Notification.From.Address))
                    {
                        throw new ConfigurationErrorsException("A <from address=\"...\"> attribute is required.", section);
                    }
                    else if ((null == result.Notification.To) || (0 == result.Notification.To.Count))
                    {
                        throw new ConfigurationErrorsException("At least one <to><recipient> element is required.", section);
                    }
                    else
                    {
                        foreach (Email email in result.Notification.To.Where(x => string.IsNullOrEmpty(x.Address)))
                        {
                            throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, "<recipient name=\"{0}\"> requires an address attribute.", email.Name), section);
                        }
                    }
                }
            }

            return result;
        }
    }
}